import  Phere from "../../qbasics/basics/Phere.js";
import  StrTo from "../../qbasics/utils/StrTo.js";
import FileUtils  from "../utils/fileUtils";
import Dx from "../../qbasics/abstract/Dx.js";
import Rx from "../../qbasics/abstract/Rx.js";
const path = require('path');
const fs = require('fs');



class Pack{
    constructor(){
        this.config;
        this.name="";
        this.rootPath="";
        this.libList=[];
        this.libMap={};
        this.depotPath=""; // 仓库路径
        this.configBuff;
    }

    init(){
        let _this=this;
        let apackPath=path.join(__dirname,'../../../../');
        let packtmp= fs.readFileSync(path.join(apackPath,'/tmp/pack.tmp') ,'utf-8' );   //临时文件
        let apackConfig= fs.readFileSync(path.join(apackPath,'/apack.config') ,'utf-8' ); //apack 配置
        let packList=packtmp.split(",");
        let apackConfigList=apackConfig.split(",");
        _this.depotPath=apackConfigList[0];
        let config={name:packList[1]}
    /*    if(fs.existsSync(path.join(packList[0],'/lib.config') )  ){
            let text= fs.readFileSync(path.join(packList[0],'/lib.config')   );   //项目配置
            let phere =new Phere();
            let buff=new  Uint8Array(text);
            phere.loadData(text);
            _this.configBuff=phere;
            let block= phere.find(1);
            let nameTab=StrTo.utf8ToNum("name");
            for(let i=0;i<block.length;i++){
                let row=   block.findRow[i+1];
                if(row&&row.is(4,nameTab)){
                    let nameNum=row.find(1);
                    config.name=  StrTo.numToUtf8(nameNum);
                }
            }
        };*/
        this.config=config;
        this.rootPath=packList[0];
        this.name=config.name;
    }

    /**
     * 拷贝 代码到 打包目录
     * @param config
     * @param name
     * @param rootPath
     */
    copyCode(){
        let _this=this;
        if(fs.existsSync(path.join(_this.rootPath,'/lib.config') )  ) {
            FileUtils.copyFs(_this.rootPath + "/lib.config", _this.rootPath + "/target/js/lib.config");
        }
        FileUtils.exists( _this.rootPath+"/src/main/js", _this.rootPath+"/target/js", FileUtils.copy );
        FileUtils.exists( _this.rootPath+"/src/main/resources", _this.rootPath+"/target/js", FileUtils.copy );

    }


    run(){
        let _this= this;
          _this.init();
          FileUtils.mkdir( path.join(_this.rootPath,"target/js"));
          FileUtils.mkdir( path.join(_this.rootPath,"target/jslib"));
          _this.copyCode( );
          let dx = new Dx();

        debugger
          readDir( path.join(_this.rootPath,"target/js"),"",dx)
        let buffList= dx.outData();
         fs.writeFileSync(_this.rootPath+"/target/"+_this.name, buffList);
        //传输到本地仓库
        fs.writeFileSync(_this.depotPath+"/"+_this.name, buffList);


      /*   //拷贝到依赖目录
         _this.copyLib();
         //把包拷贝到依赖目录下面
         fs.open(_this.rootPath+"/target/jslib/"+_this.name, 'w', '0666' , function(err, fd){
             if (err) throw err;
             if(err) {
                 console.error(err);
                 return;
             } else {
                 for(let i=0;i<buffList.length;i++){
                     let buffer =buffList[i];
                     //写入'入文件'三个字
                     fs.writeSync(fd,buffer, function (err) {
                         if(err) {
                             console.log('写入文件失败');
                             console.error(err);
                             return;
                         }
                     });
                 }


             }

         });

        let libDx = new Dx();
         readDir(  _this.rootPath+"/target/jslib/","",libDx);

         //把有依赖的jsr保存
         let libBuffList= libDx.outData();
         fs.open(_this.rootPath+"/target/"+_this.name+"_lib", 'w', '0666' , function(err, fd){
             if (err) throw err;
             if(err) {
                 console.error(err);
                 return;
             } else {
                 for(let i=0;i<libBuffList.length;i++){
                     let buffer =libBuffList[i];
                     //写入'入文件'三个字
                     fs.writeSync(fd,buffer, function (err) {
                         if(err) {
                             console.log('写入文件失败');
                             console.error(err);
                             return;
                         }
                     });
                 }


             }

         });*/
    }


    /**
     * 从仓库
     * 拷贝依赖
     */
    copyLib(){
        let _this=this;
        let phere1=_this. configBuff;
        if(phere1){
            _this.analysisConfig(phere1)
            for(let i=0;i<_this.libList.length;i++){
                let data = fs.readFileSync(path.join(_this.depotPath,_this.libList[i]+".jsr") );
                let jsr =new Jsr();
                jsr.loadData(data);

                let libconfig= jsr.findFile("lib.config");
                if(libconfig){
                    let  phere =new Phere();
                    phere.decode(libconfig);
                    _this.analysisConfig(phere);
                }

                FileUtils.copyFs(this.depotPath+"/"+_this.libList[i]+".jsr",this.rootPath+"/target/jslib/"+_this.libList[i]+".jsr");
            }
        }


    }

    /**
     * 解析依赖
     * @param config
     */
    analysisConfig(phere){
        let _this=this;
        let libNum=StrTo.utf8ToNum("lib");
        let bolck=phere.find(1);
        if(bolck){
            for(let i=0;i<bolck.length;i++){
                let row=bolck.findRow(i+1);
                if(row.is(4,libNum)){
                    let libN=    row.find(1);
                    let lib=StrTo.numToUtf8(libN);
                    _this.libMap[lib[0]]=lib;
                    _this.libList.push(lib);

                }
            }
        }

    }
}

//把文件和目录打包进jsr文件里面
function readDir( rootPath,nowPath,dx) {

    let path1=path.join(rootPath,nowPath)
    let files = fs.readdirSync(path1);//读取目录中的所有文件及文件夹（同步操作）
    files.forEach(function (fileName, index) {//遍历检测目录中的文件
        // console.log(fileName, index);//打印当前读取的文件名
        let fillPath = path.join(rootPath,nowPath,fileName)
        let file = fs.statSync(fillPath);//获取一个文件的属性
        let dir=    path.join(nowPath,fileName)
        if (file.isDirectory()) {//如果是目录的话，继续查询

            dx.addDir( fileName );//压缩对象中生成该目录
            dx.cd( fileName );//压缩对象中生成该目录
            readDir( rootPath,dir,dx);//重新检索目录文件
        } else {
            //console.log(fillPath)
            let data=fs.readFileSync(fillPath)
            var suffix = fileName.split('.').pop();
            let rx=Rx.txtToRx(data)
            if(suffix=="js"){
                rx=Rx.txtToRx(data)
            }else {
            rx=new Rx();
            rx.loadData(data)
             }


            dx.addFile( fileName ,dir,rx);//压缩目录添加文件
        }
    });
}


let pack=new Pack();
pack.run();




